<script setup lang='ts'>
import { ref, onMounted, inject, onUnmounted, watchEffect } from 'vue'
import { useRecommendStore } from '../../stores/recommend';
import { useChapterStore } from '../../stores/chapter';
import { useHistoryStore } from '../../stores/history';
import { RouterLink, useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
import { getChapterAPI, getChapterByNumAPI } from '../../apis/chapter';
import { putBookcaseAPI } from '../../apis/bookcase';
import { useUserStore } from '../../stores/user';

const store = useChapterStore()
const route = useRoute()
const chapter = ref({})
const recommendStore = useRecommendStore()

// 推荐
const recommend = ref()

const resetBackground = () => {
  // 重置背景色
  store.main.style.backgroundColor = '#e9faff'
  document.removeEventListener("keyup", (e) => { })
}

const getRecommend =  async() => {
  recommend.value = await recommendStore.getRecommend(chapter.value.type)
}

// 章节id
const id = route.params.chapterId

const previous = async () => {
  addHistory()
  const novelId = chapter.value.novelId
  const num = chapter.value.num
  if (num == 1) {
    alert('没有上一章')
    window.scrollTo(0, 0)
    return
  }
  const res = await getChapterByNumAPI(novelId, num - 1)
  chapter.value = res.data
  // 页面相关
  const targetURL = "/book/" + chapter.value.novelId + '/' + chapter.value.id
  window.history.replaceState(window.history.state, '', targetURL);
  window.scrollTo(0, 0)
  updateBookcase()
}

watchEffect(() => {
  document.title = '笔趣阁_' + chapter.value.bookName + '_' + chapter.value.title
})

const next = async () => {
  addHistory()
  const novelId = chapter.value.novelId
  const num = chapter.value.num
  if (chapter.value.isEnd) {
    alert('已经看到最后一章')
    window.scrollTo(0, 0)
    return
  }
  const res = await getChapterByNumAPI(novelId, num + 1)
  chapter.value = res.data
  // 页面相关
  const targetURL = "/book/" + chapter.value.novelId + '/' + chapter.value.id
  window.history.replaceState(window.history.state, '', targetURL);
  window.scrollTo(0, 0)
  updateBookcase()
}

const getChapter = async () => {
  const res = await getChapterAPI(id)
  chapter.value = res.data
}

const addHistory = () => {
  useHistoryStore().add({
    // 章节id
    id: chapter.value.id,
    name: chapter.value.bookName,
    type: chapter.value.type,
    author:  chapter.value.author,
    // 小说id
    novelId:chapter.value.novelId,
    chapter: chapter.value.title,
  })
}

const updateBookcase = () => {
  const bookcase = {
    novelId:chapter.value.novelId,
    readId:chapter.value.id,
    readName:chapter.value.title
  }
  if (useUserStore().token) {
    putBookcaseAPI(bookcase)
  }
}


const handleBackground = () => {
  store.main = inject('main').value
  if (store.isGreen) {
    store.main.style.backgroundColor = '#cce8cf'
  }
  // 添加键盘事件
  document.addEventListener("keyup", function (e) {
    if (e.code == 'ArrowRight') {
      next()
    } else if (e.code == 'ArrowLeft') {
      previous()
    }
  })
}

onMounted(async() => {
  handleBackground()
  await getChapter()
  getRecommend()
  setTimeout(() => {
    addHistory()
    updateBookcase()
  }, 1000);
})

onUnmounted(() => {
  resetBackground()
})


</script>

<template>

  <div class="">
    <div class="flex w-full mt-3">
      <div class="flex flex-col w-full min-h-full">
        <div class="border-2 border-blue-300">
          <h2
            class="flex items-center justify-between w-full h-10 px-2 text-xs text-gray-900 border-b border-gray-300 opacity-70 bg-color-s2"
          >
            <div class="w-3/5 text-xs nowrap">
              笔趣阁 > {{ chapter.bookName }} > {{ chapter.title }}
            </div>
            <div class="flex w-1/2 text-lg ">
              <div class="flex w-2/3 text-base">
                <span class="flex items-center mr-3 min-w-max">字体: </span>
                <el-slider
                  class="pl-1 pr-5"
                  v-model="useChapterStore().fontSize"
                  :step="2"
                  :min="14"
                  :max="30"
                  show-stops
                />
              </div>
              <div class="pl-10">
                <el-button
                  color="#8adf9c"
                  round
                  @click="useChapterStore().changeGreen"
                >护眼</el-button>
              </div>

            </div>
          </h2>
          <div class="px-5">
            <h1 class="flex items-center justify-center py-5 text-2xl text-red-600">{{ chapter.title }}</h1>
            <div
              class="mb-5 text-xs text-center text-gray-500 border-b border-gray-500 border-dashed nowrap border-opacity-70">
              新书推荐：
              <router-link
                v-for="item in recommend"
                :key="item.id"
                :to="{ path: '/book/' + item.id }"
                class="border-b border-collapse border-dotted hover:text-blue-500"
              >
                {{ item.name }}、
              </router-link>
            </div>
            <div
              class="pt-5 -mt-20"
              :style="{ fontSize: useChapterStore().fontSize + 'px', lineHeight: 1.5 }"
            >
              {{ chapter.name }} <br><br>
              <div
                v-for="(item, index) in chapter.list"
                :key="index"
              >
                <div class="px-2 text-gray-700 indent-12">
                  {{ item }} <br><br><br>
                </div>
              </div>
            </div>

            <div class="flex items-center justify-center h-10 my-3 bg-sky-300 opacity-70 ">
              <div class="flex items-center space-x-10 text-base ">

                <div
                  @click="previous"
                  class="border-b cursor-pointer border-sky-300 text-sky-800 hover:border-b-sky-800"
                >
                  上一章
                </div>


                <RouterLink
                  class="border-b border-sky-300 text-sky-800 hover:border-b-sky-800"
                  :to="{ path: '/book/' + useRoute().params.bookId }"
                >
                  目录
                </RouterLink>

                <div
                  @click="next"
                  class="text-white border-b cursor-pointer border-sky-300 hover:border-white"
                >
                  下一章
                </div>

              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<style scoped lang='css'>
.nowrap {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>